package client.ui.shadows;

import client.ui.util.MaterialColors;

import javax.swing.*;
import javax.swing.border.AbstractBorder;
import java.awt.*;
import java.awt.geom.Area;
import java.awt.geom.Rectangle2D;
import java.awt.geom.RoundRectangle2D;

/**
  * @Description 圆角矩形边框
  * @author 孔明浩
  * @Date 2020/3/31
  */
public class RoundCornerBorder extends AbstractBorder {
    //圆角弧度
    protected int arch = 12;
    //边框颜色
    protected Color colorLine;
    //边框宽度
    protected float stroke = 1.5f;

    public RoundCornerBorder(){
        this.colorLine = MaterialColors.LIGHT_BLUE_400;
    }

    public RoundCornerBorder(Color colorLine) {
        this.colorLine = colorLine;
    }

    public RoundCornerBorder(int arch, Color colorLine) {
        this.arch = arch;
        this.colorLine = colorLine;
    }

    public RoundCornerBorder(int arch, Color colorLine, float stroke){
        this.colorLine = colorLine;
        this.arch = arch;
        this.stroke= stroke;
    }

    @Override
    public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
        super.paintBorder(c, g, x, y, width, height);
        Graphics2D g2 = (Graphics2D) g.create();
        //设置画笔宽度
        g2.setStroke(new BasicStroke(stroke));
        //抗锯齿效果
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        int r = arch;
        int w = width - 1;
        int h = height - 1;
        //圆角矩形区域
        Area round = new Area(new RoundRectangle2D.Float(x,y,w,h,r,r));
        //判断是否是PopMenu,防止对象渲染错误
        if (c instanceof JPopupMenu){
            g2.setPaint(c.getBackground());
            g2.fill(round);
        } else {
            //获取父组件
            Container parent = c.getParent();
            if (parent != null){
                g2.setPaint(parent.getBackground());
                //矩形
                Area corner = new Area(new Rectangle2D.Float(x,y - stroke,width,height + stroke));
                //填充圆角
                corner.subtract(round);
                g2.fill(corner);
            }
        }
        g2.setPaint(colorLine);
        g2.draw(round);
        g2.dispose();
    }
    @Override
    public Insets getBorderInsets(Component c) {
        return new Insets(4, 12, 4, 12);
    }

    @Override
    public Insets getBorderInsets(Component c, Insets insets) {
        insets.set(4, 12, 4, 12);
        return insets;
    }
}